<?php

namespace App\Http\Library;

use Illuminate\Support\Env;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class BaiduMap
{
    protected string $api = "https://api.map.baidu.com/reverse_geocoding/v3";

    protected mixed $ak = "";

    public function __construct()
    {
        $this->ak = Env::get("BAIDU_MAP_API_KEY");
    }

    public function getAddress($longitude, $latitude){

        $key = md5("area_address_".$longitude."_".$latitude);
        $result = Cache::get($key);
        if (!$result){
            $url = $this->api."?ak={$this->ak}&output=json&coordtype=wgs84ll&location={$latitude},{$longitude}";
            $response = Http::get($url);
            $response->throw();
            if ($response->successful()){
                $res = $response->json();
                if ($res['status']==0){
                    Cache::put($key,json_encode($res['result'],JSON_UNESCAPED_UNICODE),7);
                    $address = $res['result']['addressComponent'];
                    $province = $address['province'];
                    $city = $address['city'];
                    $district = $address['district'];
                    return [
                        'province'=>rtrim($province,"市"),
                        'city'=>$city,
                        'district'=>$district,
                        'address'=>$res['result']['formatted_address'],
                    ];
                }else{
                    return [];
                }
            }else{
                return [];
            }
        }else{
            $result = json_decode($result,true);
            $address = $result['addressComponent'];
            $province = $address['province'];
            $city = $address['city'];
            $district = $address['district'];
            return [
                'province'=>rtrim($province,"市"),
                'city'=>$city,
                'district'=>$district,
                'address'=>$result['formatted_address'],
            ];
        }

    }
}
